package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.*;
import com.heima.article.entity.*;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.feign.UserFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-23
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {
    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private ITemplateService templateService;
    @Autowired
    private StringRedisTemplate redisTemplate;



    /**
     * 保存文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        ApArticle apArticle=new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        if(dto.getId()==null){
            //id为空，新增文章
            //保存文章表
            apArticle.setCreatedTime(new Date());
            this.save(apArticle);
            ApArticleContent content=new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            contentService.save(content);

            // 生成静态html  需要异步处理
            System.out.println(Thread.currentThread().getName() + " 开始调用生成静态html服务...");
            templateService.createHtml(apArticle, dto.getContent());
            System.out.println(Thread.currentThread().getName() + " 生成静态html调用结束");
            return ResponseResult.okResult(apArticle.getId());
        }else{
            //id不为空，修改文章
            this.updateById(apArticle);
            //修改内容表
            LambdaUpdateWrapper<ApArticleContent> update=new LambdaUpdateWrapper<>();
            update.eq(ApArticleContent::getArticleId,dto.getId());
            update.set(ApArticleContent::getContent,dto.getContent());
            contentService.update(update);
            return ResponseResult.okResult(apArticle.getId());
        }
    }

    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, int type) {
        if(dto.getLoaddir()==1){
            String key="hot_article_first_page_" + dto.getChannelId();;
            long start=0;
            long end=dto.getSize()-1;
            List<ApArticle> articles = new ArrayList<>();
            Set<String> strings = redisTemplate.opsForZSet().reverseRange(key, start, end);
            for (String string : strings) {
                ApArticle apArticle = JSON.parseObject(string, ApArticle.class);
                articles.add(apArticle);
            }
            if(articles.size()>=dto.getSize()){
                return ResponseResult.okResult(articles);
            }
        }
        // 构建查询条件
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        // 如果频道id不为0 添加频道查询条件
        if (dto.getChannelId() != 0) {
            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        // 如果类型是0 加载最新文章 添加查询条件:发布时间大于页面传递的最大时间
        if (type == 0) {
            query.gt(ApArticle::getPublishTime, dto.getMaxTime());
        }
        // 如果类型为1 加载下一页  添加查询条件:发布时间小于页面传递的最小时间
        if (type == 1) {
            query.lt(ApArticle::getPublishTime, dto.getMinTime());
        }
        // 已下架和已删除的文章需要排除
        query.eq(ApArticle::getIsDelete, false);
        query.eq(ApArticle::getIsDown, false);
        // 文章列表按照发布时间倒序排列
        query.orderByDesc(ApArticle::getPublishTime);
        IPage<ApArticle> page = new Page<>(1, dto.getSize());
        IPage<ApArticle> iPage = this.page(page, query);
        return ResponseResult.okResult(iPage.getRecords());

    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        // 根据id查询文章表和文章内容表
        ApArticle apArticle = this.getById(dto.getArticleId());
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent articleContent = contentService.getOne(query);
        // 构建响应对象
        Map<String, Object> map = new HashMap<>();
        map.put("config", apArticle);
        map.put("content", articleContent);
        return ResponseResult.okResult(map);

    }
    @Autowired
    private IApCollectionService collectionService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 收藏行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        User user = AppThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建收藏记录
        ApCollection collection=new ApCollection();
        collection.setEntryId(user.getUserId());
        collection.setArticleId(dto.getArticleId());
        collection.setCollectionTime(new Date());
        //判断有无记录
        LambdaQueryWrapper<ApCollection> query=new LambdaQueryWrapper<>();
        query.eq(ApCollection::getArticleId,dto.getArticleId());
        query.eq(ApCollection::getEntryId,user.getUserId());
        ApCollection one = collectionService.getOne(query);
        if(one==null){
            if(dto.getOperation()==0){
                collectionService.save(collection);
                // 发送阅读消息到kafka
                sendMessage(dto);
            }
        }else{
            if(dto.getOperation()==1){
                collectionService.remove(query);
                // 发送阅读消息到kafka
                sendMessage(dto);
            }
        }

        return ResponseResult.okResult();
    }

    /**
     * 加载文章行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticalBehavior(ArticleInfoDto dto) {
        boolean isFollow=false;
        boolean isCollection=false;
        boolean isLike=false;
        boolean isUnlike=false;
        User user = AppThreadLocalUtil.get();

        //远程查询
        LikesBehaviorDto likeDto=new LikesBehaviorDto();
        likeDto.setEquipmentId(dto.getEquipmentId());
        if(user!=null){
            likeDto.setUserId(user.getUserId());
        }
        likeDto.setArticleId(dto.getArticleId());
        ResponseResult<ApLikesBehavior> likes = behaviorFeign.getLikes(likeDto);
        if(likes.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApLikesBehavior data = likes.getData();
            if(data!=null&&data.getOperation()==0){
                isLike=true;
            }
        }
        UnLikesBehaviorDto unlikeDto=new UnLikesBehaviorDto();
        unlikeDto.setEquipmentId(dto.getEquipmentId());
        if(user!=null){
            unlikeDto.setUserId(user.getUserId());
        }
        unlikeDto.setArticleId(dto.getArticleId());
        ResponseResult<ApUnlikesBehavior> unlikes = behaviorFeign.getUnlikes(unlikeDto);
        if(unlikes.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUnlikesBehavior data = unlikes.getData();
            if(data!=null&&data.getType()==0){
                isUnlike=true;
            }
        }
        //在文章微服务查询收藏记录
        if(user!=null){
            LambdaQueryWrapper<ApCollection> query=new LambdaQueryWrapper<>();
            query.eq(ApCollection::getArticleId,dto.getArticleId());
            query.eq(ApCollection::getEntryId,user.getUserId());
            ApCollection one = collectionService.getOne(query);
            if(one!=null){
                isCollection=true;
            }
        }
        //用户微服务关注
        if (user != null) {
            FollowBehaviorDto followDto = new FollowBehaviorDto();
            followDto.setUserId(user.getUserId());
            // 根据前端传递的authorId查询作者信息,拿到作者的userId
            ApAuthor author = apAuthorService.getById(dto.getAuthorId());
            followDto.setFollowId(author.getUserId());
            ResponseResult<ApUserFollow> followResponseResult = userFeign.getFollow(followDto);
            if (followResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
                ApUserFollow userFollow = followResponseResult.getData();
                if (userFollow != null) {
                    isFollow = true;
                }
            }
        }

        Map<String,Boolean> map=new HashMap<>();
        map.put("isfollow",isFollow);
        map.put("islike",isLike);
        map.put("isunlike",isUnlike);
        map.put("iscollection",isCollection);
        return ResponseResult.okResult(map);

    }
    @Autowired
    private IApAuthorService apAuthorService;


    @Autowired
    private BehaviorFeign behaviorFeign;




    @Autowired
    private UserFeign userFeign;



    // 发送阅读消息到kafka
    private void sendMessage(CollectionBehaviorDto dto) {
        // 发送阅读消息到kafka
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setType(3);
        message.setArticleId(dto.getArticleId());
        message.setAdd(1);
        if (dto.getOperation() == 1) {
            message.setAdd(-1);
        }
        String value = JSON.toJSONString(message);
        kafkaTemplate.send(collectTopic,value);
    }

    @Value("${topic.collectTopic}")
    private String collectTopic;

}
